package com.mashibing.tank;

import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.SourceDataLine;
import java.io.IOException;

/**
 * Copyright (C) 2024 - 2024 Jasonakeke， Inc. All Rights Reserved
 *
 * @Desc :
 * @Time : 2024/10/27 15:39
 * @Author : Code_By_Jasonakeke
 * @Email : 2284037977@qq.com
 * @Class : Audio
 * @IDE : IntelliJ IDEA
 */
public class Audio {

	private byte[] b = new byte[1024 * 1024 * 15];

	private AudioFormat audioFormat = null;

	private SourceDataLine sourceDataLine = null;

	private DataLine.Info dataLineInfo = null;

	private AudioInputStream audioInputStream = null;


	public Audio(String fileName) {
		try {
			audioInputStream = AudioSystem.getAudioInputStream(Audio.class.getClassLoader().getResourceAsStream(fileName));
			audioFormat = audioInputStream.getFormat();
			dataLineInfo = new DataLine.Info(SourceDataLine.class, audioFormat);
			sourceDataLine = (SourceDataLine) AudioSystem.getLine(dataLineInfo);
			// FloatControl volCtrl  = (FloatControl) sourceDataLine.getControl(FloatControl.Type.MASTER_GAIN);
			// volCtrl.setValue(-40);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	public void loop() {
		try {
			while (true) {
				int length = 0;
				sourceDataLine.open(audioFormat, 1024 * 1024 * 15);
				sourceDataLine.start();
				// System.out.println(audioInputStream.markSupported());
				audioInputStream.mark(12358946);
				while ((length = audioInputStream.read(b)) > 0) {
					sourceDataLine.write(b, 0, length);
				}
				audioInputStream.reset();

				sourceDataLine.drain();
				sourceDataLine.close();

			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void play() {
		try {
			byte[] bytes = new byte[1024 * 5];
			int length = 0;
			sourceDataLine.open(audioFormat, 1024 * 5);
			sourceDataLine.start();
			// System.out.println(audioInputStream.markSupported());
			audioInputStream.mark(12358946);
			while ((length = audioInputStream.read(b)) > 0) {
				sourceDataLine.write(b, 0, length);
			}
			audioInputStream.reset();

			sourceDataLine.drain();
			sourceDataLine.close();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	public void close(){
		try {
			audioInputStream.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) {
		Audio audio = new Audio("audio/war1.wav");
		audio.loop();
	}
}
